<?php


namespace App\Lib\Upload;

use App\Lib\Utils;
use Lib\Utils\CommonUtils;

/**
 * 上传基类
 * @package Lib\UploadApp
 */
class Base
{

    private $type = null;
    private $request = null;

    public function __construct($request, $type = null)
    {
        $this->request = $request;
        if (empty($type)){
            $files = $this->request->getSwooleRequest()->files;
            $types = array_keys($files);
            $this->type = $types[0];
        }else{
            $this->type = $type;
        }
    }

    public function upload(){
        if($this->type != $this->fileType) {
            return false;
        }

        $uploadedFile = $this->request->getUploadedFile($this->type);

        $this->size = $uploadedFile->getSize();

        $this->clientMediaType = $uploadedFile->getClientMediaType();

        $fileName = $uploadedFile->getClientFileName();
        $file = $uploadedFile->getFile($fileName);

        $flag = $uploadedFile->moveTo($file);
        if (!empty($flag)){
            return $file;
        }
        return false;
    }

    public function getFile($fileName) {
        $pathinfo = pathinfo($fileName);
        $extension = $pathinfo['extension'];

        $dirname = "/".$this->type . "/". date("Y") . "/" . date("m");
        $dir = EASYSWOOLE_ROOT  . "/webroot" . $dirname;
        if(!is_dir($dir)) {
            mkdir($dir, 0777 , true);
        }

        $basename = "/" .CommonUtils::getFileKey($fileName) . ".".$extension;

        $this->file = $dirname . $basename;
        return$dir  . $basename;

    }

    public function checkMediaType() {
        $clientMediaType = explode("/", $this->clientMediaType);
        $clientMediaType = $clientMediaType[1] ?? "";
        if(empty($clientMediaType)) {
            throw new \Exception("上传{$this->type}文件不合法");
        }
        if(!in_array($clientMediaType, $this->fileExtTypes)) {
            throw new \Exception("上传{$this->type}文件不合法");
        }

        return true;
    }
    public function checkSize() {
        if(empty($this->size)) {
            return false;
        }

        // todo
        //
        //
    }




}